﻿using ConfExpert.Forms.Depo.Istek;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevTeam;
using System;
using System.Data;

namespace ConfExpert.Forms.Depo
{
    public partial class Transfer : XPopupForm
    {
        int CKBatchId = 0;
        bool KDept = false;
        DataTable se = new DataTable();
        DataTable sel = new DataTable();
        public Transfer(DataTable _selectedRolls, DataTable _selectedArts, bool _KDept, int CKBatchId = 0)
        {
            if (CKBatchId > 0)
            {
                this.CKBatchId = CKBatchId;
                this.Opacity = 0;
            }

            InitializeComponent();

            KDept = _KDept;
            sel = _selectedRolls;
            se = _selectedArts;
        }

        int userId = WhoAmI;
        private void StokTransfer_Load(object sender, EventArgs e)
        {
            if (CKBatchId > 0)
            {
                DataRow r = AppSession.Lookups.CKBatch.FindByCKBatchId(CKBatchId);
                gleBrand.EditValue = r["BrandId"].ToInt();
                gleSezon.EditValue = r["SezonId"].ToInt();
                gleOrderRef.EditValue = r["Notes"].ToStr();
                DoIt(null);
            }

            if (isKD)
                userId = -1; //Tüm markalar

            gleOrderRef.Properties.NullText = string.Empty;

            DataTable dt = Session.DataManager.ExecuteDataTable("GetMyBrands2", userId);
            DevExpress.XtraEditors.Repository.RepositoryItemGridLookUpEdit riMyBrands = GetCustomGLE(dt, "Name", "BrandId");
            gleBrand.Properties.Assign(riMyBrands);

            btnTransfer.Click += new EventHandler(btnTransfer_Click);
            chkIdle.CheckedChanged += new EventHandler(chkIdle_CheckedChanged);

            gleSezon.Properties.Assign(RI(Rp.Sezon));

            cmbSebebi.Properties.TextEditStyle =
            cmbTercih.Properties.TextEditStyle = TextEditStyles.DisableTextEditor;
            cmbTercih.SelectedIndexChanged += new EventHandler(cmbTercih_SelectedIndexChanged);
            this.Shown += new EventHandler(Transfer_Shown);

            gleSezon.EditValueChanged += gleSezon_EditValueChanged;
            gleBrand.Closed += gleBrand_Closed;
            gleBrand.EditValueChanged += gleBrand_EditValueChanged;

            gleBrand.MakeCompulsory(lblMarka, "Doldurulması zorunlu alan.");
            gleSezon.MakeCompulsory(lblSezon, "Doldurulması zorunlu alan.");
            gleOrderRef.MakeCompulsory(lblOrderRef, "Ayrılmış olduğu halde OrderRef. girmeden devam edemezsiniz.");
        }

        DataTable dtSODetay;
        void gleBrand_EditValueChanged(object sender, EventArgs e)
        {
            int BrandId = gleBrand.EditValue.ToInt();

            dtSODetay = ExecuteDataTable("GetOrderRefByUser", userId, BrandId);
            gleOrderRef.Properties.Assign(GetIntellisensedRI(dtSODetay));
            gleOrderRef.Properties.ProcessNewValue -= new ProcessNewValueEventHandler(ri_ProcessNewValue2);
            gleOrderRef.Properties.ProcessNewValue += new ProcessNewValueEventHandler(ri_ProcessNewValue2);

            gleOrderRef.Properties.View.Columns["Name"].Caption = "OrderRef.";
            gleOrderRef.Properties.View.Columns["BrandId"].ColumnEdit = RI(Rp.Brand);
            gleOrderRef.Properties.View.Columns["BrandId"].Caption = "Marka";
            gleOrderRef.Properties.View.Columns["SezonId"].ColumnEdit = RI(Rp.Sezon);
            gleOrderRef.Properties.View.Columns["SezonId"].Caption = "Sezon";

            gleOrderRef.Closed -= gleOrderRef_Closed;
            gleOrderRef.Closed += gleOrderRef_Closed;

            gleOrderRef.Properties.View.BestFitColumns();
            ValidateAll(false);

            switch (BrandId)
            {
                case 1:
                case 290:
                    lblSebebi.Visible = cmbSebebi.Visible = true;
                    break;

                default:
                    lblSebebi.Visible = cmbSebebi.Visible = false;
                    cmbSebebi.EditValue = null;
                    break;
            }
        }

        void gleBrand_Closed(object sender, ClosedEventArgs e)
        {
            switch (gleBrand.EditValue.ToInt())
            {
                case 1:
                case 290:
                    gleOrderRef.EditValue = null;
                    chkIdle.Checked = true;
                    gleSezon.EditValue = 3;

                    if (!KDept)
                        gleSezon.Enabled = gleOrderRef.Enabled = chkIdle.Enabled = false;
                    break;

                default:
                    gleSezon.Enabled = gleOrderRef.Enabled = chkIdle.Enabled = true;
                    break;
            }
        }

        private void gleSezon_EditValueChanged(object sender, EventArgs e)
        {
            ValidateAll(false);
        }

        void gleOrderRef_Closed(object sender, ClosedEventArgs e)
        {
            gleSezon.EditValueChanged -= gleSezon_EditValueChanged;
            gleBrand.EditValueChanged -= gleBrand_EditValueChanged;

            if (dtSODetay.Select("Name='" + gleOrderRef.EditValue.ToStr() + "'").Length > 0)
            {
                DataRow row = dtSODetay.Select("Name='" + gleOrderRef.EditValue.ToStr() + "'")[0];
                if (row["BrandId"] != DBNull.Value)
                    gleBrand.EditValue = row["BrandId"].ToInt();

                if (row["SezonId"] != DBNull.Value)
                    gleSezon.EditValue = row["SezonId"].ToInt();
            }

            gleSezon.EditValueChanged += gleSezon_EditValueChanged;
            gleBrand.EditValueChanged += gleBrand_EditValueChanged;

            ValidateAll(false);
        }

        void cmbTercih_SelectedIndexChanged(object sender, EventArgs e)
        {
            deTill.Visible = cmbTercih.SelectedIndex == 2;
            cmbSure.Visible = cmbTercih.SelectedIndex == 1;
        }

        void Transfer_Shown(object sender, EventArgs e)
        {
            gleBrand.Focus();
        }


        void chkIdle_CheckedChanged(object sender, EventArgs e)
        {
            gleOrderRef.Enabled = !chkIdle.Checked;
            if (chkIdle.Checked)
                gleOrderRef.EditValue = null;

            ValidateAll(false);
        }

        void btnTransfer_Click(object sender, EventArgs e)
        {
            DataTable dtPopUp = ExecuteDataTable("GetIstekLines", sel.Serialize(), intParse(gleBrand.EditValue), WhoAmI);

            if (dtPopUp.Rows.Count > 0)
            {
                using (IstekOnayi IstekOnay = new IstekOnayi(dtPopUp))
                {
                    if (IstekOnay.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                        DoIt(IstekOnay.xmlData);
                    else
                    {
                        IstekOnay.Dispose();
                        IstekOnay.Close();
                        return;
                    }
                }
            }
            else
                DoIt(null);
        }

        private void DoIt(string xmlFiyatData)
        {
            if (!KDept)
                if (cmbSebebi.EditValue == null && cmbSebebi.Visible)
                {
                    XtraMessageBox.Show("Sebep boş olamaz!");
                    return;
                }
            if (gleOrderRef.EditValue == null && !chkIdle.Checked)
            {
                XtraMessageBox.Show("OrderRef boş olamaz!");
                return;
            }
            if (intParse(gleBrand.EditValue) == 0)
            {
                XtraMessageBox.Show("Marka boş olamaz!");
                return;
            }
            if (intParse(gleSezon.EditValue) == 0)
            {
                XtraMessageBox.Show("Sezon boş olamaz!");
                return;
            }

            string xmlSel = sel.Serialize();
            string xmlSe = se.Serialize();
            string str = string.Empty;

            DataTable dtBuffer = ExecuteDataTable((KDept ? "TransferKontrolSU" : "TransferKontrol3"),  // 'Super User'lar ve KDept icin ayri bir prosedur cagir
                xmlSel,
                xmlSe,
                gleOrderRef.EditValue,
                intParse(gleBrand.EditValue),
                intParse(gleSezon.EditValue),
                WhoAmI,
                chkIdle.Checked,
                'A',
                cmbSebebi.Text,
                xmlFiyatData
                );

            if (dtBuffer.Rows.Count > 0)
            {
                if (dtBuffer.Columns["intVal"] != null)
                    if (dtBuffer.Rows[0]["intVal"] != DBNull.Value)
                    {
                        string oid = string.Empty;
                        foreach (DataRow r in dtBuffer.Rows)
                            oid += r["intVal"].ToStr() + Environment.NewLine;

                        if (dtBuffer.Rows[0]["strVal"].ToStr() != string.Empty)
                            if (dtBuffer.Rows[0]["strVal"].ToStr().StartsWith("Sahibi Karbel"))
                                XtraMessageBox.Show("Sahibi Karbel olmayan topları başka bir depoya transfer edemezsiniz. Şu toplar bu kuralı ihlal ediyor:\n\n" + oid, "İşlem başarısız");
                            else
                                XtraMessageBox.Show("Yetkili olmadığınız iki depo arasında transfer yapamazsınız. Şu toplar bu kuralı ihlal ediyor:\n\n" + oid, "İşlem başarısız");

                        return;
                    }

                str = "Onay gerektiren transferler sorumlu kişilere iletildi. Takip için IstekId: " + dtBuffer.Rows[0]["strVal"];
            }

            ExecuteNonQuery("Transfer3",
                xmlSel,
                xmlSe,
                gleOrderRef.EditValue.ToStr(),
                intParse(gleBrand.EditValue),
                intParse(gleSezon.EditValue),
                WhoAmI,
                cmbSebebi.Text
                );

            if (str != string.Empty)
                XtraMessageBox.Show(str);

            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }
    }
}